
import PlatformUtil from "./PlatformUtil";
import httpUtils from "./XmlHttpTool";
import StartGameView from "./StartGameView";
import xorEncryptionData from "./Tool/xor";
import allVariableJs from "./allVariable";
cc.Class({
    extends: cc.Component,

    properties: {
        loginBtn: cc.Button,
        infoLabel: {
            default: null,
            type: cc.Label,
        },
        startGamejs: StartGameView,
        userInfoDic: "",
        showHubProjess: cc.Node,
        SvprogressPrefab: cc.Prefab,
        logonode: cc.Node,
        guestBtn: cc.Button
    },



    onLoad() {



        var changebig2 = cc.scaleTo(0.2, 1.2);

        var finish = cc.callFunc(function () {

            var changesmail2 = cc.scaleTo(0.1, 1.0);
            this.logonode.runAction(changesmail2)

        }, this);

        var seq = cc.sequence(changebig2, finish)

        this.logonode.runAction(seq)

        sdkbox.PluginFacebook.init();

        PlatformUtil.init();
        PlatformUtil.platform.init(this);
        this.fbInit();

        var tokenstring = PlatformUtil.platform.getStorage("tokenCode")
        console.log("是否存在token", tokenstring)
        if (sdkbox.PluginFacebook.isLoggedIn()) {

            PlatformUtil.init();
            PlatformUtil.platform.init(this);
            PlatformUtil.platform.params["token"] = tokenstring
            this.startGamejs.getUserInfoHttp()
            this.node.active = false

        } else {

        }

        // if (sdkbox.PluginFacebook.isLoggedIn()){
        //     console.log("facebook已经登录过了")
        //     // PlatformUtil.init();
        //     // PlatformUtil.platform.init(this);
        //     // PlatformUtil.platform.params["token"]=allVariableJs.userToken
        //     // this.startGamejs.getUserInfoHttp()
        //     // this.node.active=false
        // }else{
        //     console.log("facebook第一次登录")
        //      PlatformUtil.init();
        //      PlatformUtil.platform.init(this);
        //      this.fbInit();

        //     // if (cc.sys.isNative&&cc.sys.os==cc.sys.OS_IOS) {
        //     //     let ret = jsb.reflection.callStaticMethod("AdMaster","showAd:","token");
        //     //     console.log("从本地取出来的token",ret)
        //     //     if(ret){

        //     //         PlatformUtil.init();
        //     //         PlatformUtil.platform.init(this);
        //     //         PlatformUtil.platform.params["token"]=ret
        //     //         allVariableJs.userToken=ret
        //     //         this.startGamejs.getUserInfoHttp()
        //     //         this.node.active=false

        //     //     }else{
        //     //         console.log("第一次登录")
        //     //         PlatformUtil.init();
        //     //         PlatformUtil.platform.init(this);
        //     //         this.fbInit();
        //     //     }     
        //     // }
        // }

        this.isshowGuestLogin()

    },

    loginGameSence: function () {


        this.login();
        console.log("准备登录", sdkbox.PluginFacebook.isLoggedIn())

    },

    isshowGuestLogin: function () {

        var that = this
        httpUtils.NhttpPost("/quick_users/init", { "storetype": "apple" }, function (res) {
            console.log("是否显示游客登录按钮", JSON.stringify(res))
            if (res["v"] == 1) {
                that.guestBtn.node.active = true
            } else {

            }
        })

    },

    guestLogin: function () {

        console.log("游客登录")
        this.loginGame('com.taoqi001.mp_marmot_facebook');


    },



    check_plugin: function () {
        if ('undefined' == typeof (sdkbox)) {
            this.showInfo('sdkbox is undefined')
            return false;
        }
        if ('undefined' == typeof (sdkbox.PluginFacebook)) {
            this.showInfo('sdkbox.PluginFacebook is undefined')
            return false;
        }

        return true;
    },

    showInfo: function (text) {

        console.log("登录提示", text)

    },

    fbInit: function () {

        if (!this.check_plugin()) {
            return
        }

        var self = this


        sdkbox.PluginFacebook.setListener({
            onLogin: function (isLogin, msg) {
                if (isLogin) {
                    self.showInfo("login successful");
                    var userId = sdkbox.PluginFacebook.getUserID();
                    console.log('用户id', userId)


                } else {
                    self.showInfo("login failed");
                }
            },

            onGetUserInfo(userInfo) {


                self.userInfoDic = userInfo
                console.log('登录成功数据', JSON.stringify(this.userInfoDic))
                self.loginGame(userInfo["id"])
            },
            onAPI: function (tag, data) {

                self.showInfo('onAPI:' + tag)

            },
            onSharedSuccess: function (data) {
                self.showInfo("share successful");

                // if ('undefined' != typeof(sdkbox) && 'undefined' == typeof(sdkbox.PluginGoogleAnalytics)) {
                //     sdkbox.PluginGoogleAnalytics.logEvent('facebook', 'share', 'share success', 0);
                // }
            },
            onSharedFailed: function (data) {
                self.showInfo("share failed");
            },
            onSharedCancel: function () {
                self.showInfo("share canceled");
            },
            onPermission: function (isLogin, msg) {
                if (isLogin) {
                    self.showInfo("request permission successful");
                } else {
                    self.showInfo("request permission failed");
                }
            }
        });
    },

    login: function () {
        if (!this.check_plugin()) {
            this.showInfo("校验成功")
            return
        }

        if (sdkbox.PluginFacebook.isLoggedIn()) {
            this.showInfo("you has already login")
            if (cc.isValid(this.showHubProjess)) {
                this.showHubProjess.destroy();
            }
            this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
            this.node.addChild(this.showHubProjess);
            this.showHubProjess.getComponent('SVProgressView').init("您已经登录了")

            let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(5), cc.fadeOut(1));
            this.showHubProjess.runAction(action);

            return
        }

        sdkbox.PluginFacebook.login();

    },

    logout: function () {
        if (!this.check_plugin()) {
            return
        }

        if (!sdkbox.PluginFacebook.isLoggedIn()) {

            this.showInfo("you has already logout")
            return
        }

        sdkbox.PluginFacebook.logout();
    },

    reqReadPermission: function () {
        if (!this.check_plugin()) {
            return
        }

        sdkbox.PluginFacebook.requestReadPermissions(["public_profile", "email"]);
    },

    reqWritePermission: function () {
        if (!this.check_plugin()) {
            return
        }

        sdkbox.PluginFacebook.requestPublishPermissions(["publish_actions"]);
    },

    shareLink: function () {
        if (!this.check_plugin()) {
            return
        }

        var info = new Object();
        info.type = "link";
        info.link = "http://www.cocos2d-x.org";
        info.title = "cocos2d-x";
        info.text = "Best Game Engine";
        info.image = "http://cocos2d-x.org/images/logo.png";
        sdkbox.PluginFacebook.share(info);

        if ('undefined' != typeof (sdkbox) && 'undefined' == typeof (sdkbox.PluginGoogleAnalytics)) {
            sdkbox.PluginGoogleAnalytics.logEvent('facebook', 'share', 'share link begin', 0);
        }
    },

    dialogLink: function () {
        if (!this.check_plugin()) {
            return
        }

        var info = new Object();
        info.type = "link";
        info.link = "http://www.cocos2d-x.org";
        info.title = "cocos2d-x";
        info.text = "Best Game Engine";
        info.image = "http://cocos2d-x.org/images/logo.png";
        sdkbox.PluginFacebook.dialog(info);

        if ('undefined' != typeof (sdkbox) && 'undefined' == typeof (sdkbox.PluginGoogleAnalytics)) {
            sdkbox.PluginGoogleAnalytics.logEvent('facebook', 'share', 'dialog share begin', 0);
        }
    },

    invite: function () {
        if (!this.check_plugin()) {
            return
        }

        sdkbox.PluginFacebook.inviteFriends(
            "https://fb.me/322164761287181",
            "http://www.cocos2d-x.org/attachments/801/cocos2dx_portrait.png");

    },

    loginGame: function (userIdString) {

        if (cc.isValid(this.showHubProjess)) {
            this.showHubProjess.destroy();
        }
        this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
        this.node.addChild(this.showHubProjess);
        this.showHubProjess.getComponent('SVProgressView').init("Logging in..Please Waiting")

        let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(10), cc.fadeOut(1));
        this.showHubProjess.runAction(action);

        var resultstr = xorEncryptionData.encryptionData(userIdString, PlatformUtil.platform.params)

        console.log("code加密", resultstr)
        var that = this
        httpUtils.httpPost("/quick_users/wxregister", { "regtype": 1, "code": resultstr }, function (res) {


            console.log("获取token", res["token"])
            PlatformUtil.platform.setStorage({key:"tokenCode", value:res["token"]})
            var tokenstring = PlatformUtil.platform.getStorage("tokenCode")
            console.log("本地token", tokenstring)
            if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
                let ret = jsb.reflection.callStaticMethod("AdMaster", "sendCopyMessage:", res["token"]);
            }

            allVariableJs.userToken = res["token"]
            console.log("全新字典1", JSON.stringify(PlatformUtil.platform.params))
            PlatformUtil.platform.params["token"] = res["token"]
            console.log("全新字典2", JSON.stringify(PlatformUtil.platform.params))
            that.save_UserInfo(userIdString)


        }, function (failres) {

            console.log("时间超时1", JSON.stringify(failres))
            if (cc.isValid(that.showHubProjess)) {
                that.showHubProjess.destroy();
            }
            that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
            that.node.addChild(that.showHubProjess);
            that.showHubProjess.getComponent('SVProgressView').init("登录超时,请重新登录")

            let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(5), cc.fadeOut(1));
            that.showHubProjess.runAction(action);
            that.logout()
        },
            function () {
                console.log("时间超时2")
                if (cc.isValid(that.showHubProjess)) {
                    that.showHubProjess.destroy();
                }
                that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
                that.node.addChild(that.showHubProjess);
                that.showHubProjess.getComponent('SVProgressView').init("登录超时,请重新登录")

                let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(5), cc.fadeOut(1));
                that.showHubProjess.runAction(action);
                that.logout()
            }
        )
    },


    save_UserInfo: function (userIdString) {

        var that = this
        console.log("用户头像", this.userInfoDic["picture_url"])
        httpUtils.httpPost("/users/save_user_info", { "avatar": this.userInfoDic["picture_url"], "name": this.userInfoDic["name"], "gender": "0" }, function (res) {

            console.log("存储用户信息", JSON.stringify(res))
            that.startGamejs.getUserInfoHttp()
            that.node.active = false


        }, function (failres) {
            console.log("时间超时3")
            if (cc.isValid(that.showHubProjess)) {
                that.showHubProjess.destroy();
            }
            that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
            that.node.addChild(that.showHubProjess);
            that.showHubProjess.getComponent('SVProgressView').init("登录超时,请重新登录")

            let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(5), cc.fadeOut(1));
            that.showHubProjess.runAction(action);
            that.logout()
        },
            function () {
                console.log("时间超时4")
                if (cc.isValid(that.showHubProjess)) {
                    that.showHubProjess.destroy();
                }
                that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
                that.node.addChild(that.showHubProjess);
                that.showHubProjess.getComponent('SVProgressView').init("登录超时,请重新登录")

                let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(5), cc.fadeOut(1));
                that.showHubProjess.runAction(action);
                that.logout()
            })

    },
    start() {

    },

});
